package com.JUC.cha10.sec01;

import java.util.Random;
import java.util.concurrent.TimeUnit;

class House {//资源类

    int saleCount = 0;

    public synchronized void saleHouse() {
        ++saleCount;
    }

    /*ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>(){
        @Override
        protected Integer initialValue() {
            return 0;
        }
    };*/

    ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);

    public void saleHouseByThreadLocal(){
        threadLocal.set(threadLocal.get() + 1);
    }

}

/**
 * ThreadLocal
 * 需求1：5个销售卖房子，集团高层只关心销售总量的准确统计数
 * <p>
 * 需求2：5个销售卖完随机数房子，各自独立销售额度，自己业绩按提成走，分灶吃饭
 */
public class ThreadLocalDemo {

    public static void main(String[] args) {

        House house = new House();

        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                int size = new Random().nextInt(5) + 1;//销售额：1~5
                for (int j = 0; j < size; j++) {
                    house.saleHouse();
                    house.saleHouseByThreadLocal();
                }
                System.out.println(Thread.currentThread().getName() + "线程\t销售额：" + house.threadLocal.get());
            }, String.valueOf(i)).start();
        }

        // 暂停几秒钟线程
        try {
            TimeUnit.MILLISECONDS.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "\t总销售额：" + house.saleCount);


    }
}
